<?php
  include __DIR__."/config/cors.php";
  include __DIR__."/sendMail.php";
  include __DIR__."/database.php";

  $email = @$_POST['email'];

  if(!isset($email)){
    echo json_encode([
        "code" => 202,
        "msg"=> "缺少必要参数"
      ]);
      exit;
  }
  $db = new DB();
  $sql1 = "select * from user where mail = '$email'";
  $data = $db->selectOne($sql1);
  $uid = @$data['id'];
  if (is_array($data) and count($data) > 0) {
    $result = sendMail($email);
    if($result['code'] == 200){
        $authcode = $result['data'];
        $sql2 = "insert into authcode(uid,authcode) values('$uid','$authcode')";
            if ($db->insert($sql2)) {
                echo json_encode([
                    "code" => 200,
                    "msg"=> "邮件发送成功,请注意查收",
                    "data"=> $uid
                  ]);
            } else {
                echo json_encode([
                    "code" => 204,
                    "msg"=> "邮件发送失败: " . $data
                ]);
            }
      }else{
        echo json_encode($result);
      }
  }else {
    if(is_array($data) and count($data) == 0){
        echo json_encode([
            "code" => 204,
            "msg"=> "该邮箱尚未绑定账号"
        ]);
    }else {
        echo json_encode([
            "code" => 204,
            "msg"=> "查询失败: " . $data
          ]);
    }
}
?>